package com.yupi.shanoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.yupi.shanoj.model.dto.question.JudgeCase;
import com.yupi.shanoj.model.dto.question.JudgeConfig;
import com.yupi.shanoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.shanoj.model.entity.Question;
import com.yupi.shanoj.model.enums.JudgeInfoMessageEnum;

import java.util.List;

public class DefaultStrategy implements JudgeStrategy{
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {

        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();
        Long memory = judgeInfo.getMemory();
        Long time = judgeInfo.getTime();
        JudgeInfo judgeInfoRes = new JudgeInfo();
        judgeInfoRes.setMemory(memory);
        judgeInfoRes.setTime(time);
        JudgeInfoMessageEnum judgeInfoMessageEnum= JudgeInfoMessageEnum.ACCEPTED;
        judgeInfoRes.setMessage(judgeInfoMessageEnum.getValue());
        if(outputList.size()!= inputList.size()){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoRes.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoRes;
        }
        //依次判断每一项输出和预期输出是否相等
        for(int i=0;i<judgeCaseList.size();i++){
            JudgeCase judgeCase = judgeCaseList.get(i);
            if(!judgeCase.getOutput().equals(outputList.get(i))){
                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoRes.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoRes;
            }
        }
        //判题限制
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long needMemoryLimit = judgeConfig.getMemoryLimit();
        Long needTimeLimit = judgeConfig.getTimeLimit();
        if(memory>needMemoryLimit){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoRes.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoRes;
        }
        if(time>needTimeLimit){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoRes.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoRes;
        }
        judgeInfoRes.setMessage(judgeInfoMessageEnum.getValue());
        return judgeInfoRes;
    }
}
